package com.example.demo.util;

import java.io.IOException;
import lombok.RequiredArgsConstructor;

import lombok.extern.slf4j.Slf4j;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * @author jiangjinwu
 * @version 1.0
 * @since 2025/10/8 23:20
 */

@Slf4j

public class HttpUtil {
  static OkHttpClient client = new OkHttpClient().newBuilder()
      .readTimeout(0, java.util.concurrent.TimeUnit.SECONDS)
      .writeTimeout(0, java.util.concurrent.TimeUnit.SECONDS)
      .callTimeout(0, java.util.concurrent.TimeUnit.SECONDS)
      .eventListener(new okhttp3.EventListener() {
        @Override
        public void callFailed(Call call, IOException e) {
          System.err.println("请求失败: " + e.getMessage());
          if (e.getMessage().contains("connect timed out")) {
            System.err.println("类型: 连接超时");
          } else if (e.getMessage().contains("read timed out")) {
            System.err.println("类型: 读取超时");
          } else if (e.getMessage().contains("write timed out")) {
            System.err.println("类型: 写入超时");
          }
        }
      })
      .build();
  public static String send(String url,String method,String bodyJson,String token) throws IOException {
    logger.info("url:"+url+"body:"+bodyJson);
    MediaType mediaType = MediaType.parse("application/json");
    RequestBody body = RequestBody.create(mediaType, bodyJson);
    Request request = new Request.Builder()
        .url(url)
        .method(method, body)
        .addHeader("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
        .addHeader("Authorization", "Bearer "+ token)
        .addHeader("Content-Type", "application/json")
        .build();
    try (Response response = client.newCall(request).execute()) {
      if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
      try (ResponseBody responseBody = response.body()) {
        if (body == null) throw new IOException("Response body is null");
        String result = responseBody.string();
        System.out.println(result);
        return result;
      }
    }
  }

  public static String post(String url,String bodyJson,String token) throws IOException {
     return send(url,"POST",bodyJson,token);
  }
}
